<template>
  <div class="app-container">
    <el-row :gutter="20">
        <el-col :span="4" :xs="24">
          <div class="head-container">
              <el-tree
                :data="warehouseOptions"
                :props="{ label: 'name', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="warehouseTreeRef"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
              />
          </div>
        </el-col>
        <el-col :span="20" :xs="24">
          <el-form class="formBox" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <template v-for="(column, index) in columns">
              <template v-if="column.query">
                <el-form-item v-if="column.queryType=='input'" :label="column.label" :prop="column.prop" :key="index">
                  <el-input
                    v-model="queryParams[column.prop]"
                    :placeholder="`请输入${column.label}`"
                    clearable
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
                <el-form-item v-if="column.queryType=='select'" :label="column.label" :prop="column.prop" :key="index">
                  <el-select v-model="queryParams.warehouseStatus" :placeholder="`请输入${column.label}`" clearable style="width:100%">
                    <el-option
                      v-for="dict in wms_warehouse_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </template>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['warehouseManagement:warehouse:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['warehouseManagement:warehouse:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['warehouseManagement:warehouse:remove']"
              >删除</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['warehouseManagement:warehouse:export']"
              >导出</el-button>
            </el-col> -->
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <template v-for="(column, index) in columns">
              <el-table-column
                :key="index"
                :min-width="column.minWidth"
                :label="column.label"
                align="center"
                :prop="column.prop"
                :sortable="column.sortable"
                v-if="!columns[index].visible"
              >
                <template #default="scope">
                  <div v-if="column.prop === 'warehouseId'">
                    <span>{{ getName("warehouse",scope.row.warehouseId) }}</span>
                  </div>
                  <div v-else-if="column.prop === 'areaId'">
                    <span>{{ getName("area",scope.row.areaId) }}</span>
                  </div>
                  <div v-else-if="column.prop === 'shelfId'">
                    <span>{{ getName("shelf",scope.row.shelfId) }}</span>
                  </div>
                  <div v-else-if="column.prop === 'warehouseStatus'">
                    <span>{{ getName("warehouseStatus",scope.row.warehouseStatus) }}</span>
                  </div>
                  <div v-else-if="column.prop === 'status'">
                    <span>{{ getName("status",scope.row.status) }}</span>
                  </div>
                  
                  <div v-else>
                    {{scope.row[column.prop]}}
                  </div>
                </template>
              </el-table-column>
            </template>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
              <template #default="scope">
                <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['warehouseManagement:warehouse:edit']">修改</el-button> -->
                <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['warehouseManagement:warehouse:remove']">删除</el-button> -->
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
    </el-row>
 

    <!-- 添加或修改仓库管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form :ref="`${refMap[node]}`" :model="form" :rules="data.rules" label-width="100px">
        <template v-for="(item,index) in columns">
          <template v-if="item.dialogVis">
            <el-form-item v-if="item.type=='input'" :label="item.label" :prop="item.prop" :key="index" :label-width="`${item.width?'120px':'100px'}`">
              <el-input v-model="form[item.prop]" :placeholder="`请输入${item.label}`" />
            </el-form-item>
            <el-form-item  v-else-if="item.type=='date'" :label="item.label" :prop="item.prop" >
              <el-date-picker clearable
                v-model="form[item.prop]"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="`请选择${item.label}`">
              </el-date-picker>
            </el-form-item>
            <el-form-item v-else-if="item.type=='radio'" :label="item.label" :prop="item.prop" >
              <el-radio-group v-model="form[item.prop]">
                <el-radio
                  v-for="dict in wms_warehouse_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Warehouse">
import { listWarehouse, getWarehouse, delWarehouse, addWarehouse, updateWarehouse,getWarehouseAll } from "@/api/warehouseManagement/warehouse";
import { listArea, getArea, delArea, addArea, updateArea,listAreaByPid } from "@/api/area/area";
import { listShelf, getShelf, delShelf, addShelf, updateShelf,listShelfByPid } from "@/api/shelf/shelf";
import { listLocation, getLocation, delLocation, addLocation, updateLocation,listLocationByPid,addAllLocation } from "@/api/location/location";
import { onMounted,nextTick } from "vue";
const { proxy } = getCurrentInstance();
const { wms_warehouse_status } = proxy.useDict('wms_warehouse_status');

const tableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const columns = ref([])
const node = ref(1);
const clickNode = ref({})

const refMap = ref({
  1:"warehouseRef",
  2:"areaRef",
  3:"shelfRef",
  4:"locationRef",
})

// 列显隐信息
const warehouseColumns = ref([
  { key: 0, label: `仓库ID`, prop: `id`, minWidth: 135, visible: false,dialogVis:false,type:"input",},
  { key: 0, label: `仓库编号`, prop: `warehouseNo`, minWidth: 200, visible: false,dialogVis:false,type:"input",query:true,queryType:'input'},
  { key: 1, label: `仓库名称`, prop: `name`, minWidth: 135,  visible: false ,dialogVis:true,type:"input",query:true,queryType:'input'},
  { key: 2, label: `仓库位置`, prop: `location`, minWidth: 135, visible: false,dialogVis:true,type:"input",query:false,queryType:'input' },
  { key: 3, label: `仓库容量`, prop: `capacity`, minWidth: 135,  visible: false,dialogVis:true,type:"input", },
  { key: 6, label: `仓库描述`, prop: `description`, minWidth: 135, visible: false,dialogVis:true,type:"input" },
  { key: 7, label: `仓库类型`, prop: `warehouseStatus`, minWidth: 135,  visible: false,dialogVis:true,type:"radio",query:true,queryType:'select' },
  { key: 8, label: `仓储费/天`, prop: `storageFee`, minWidth: 135, visible: false,dialogVis:true,type:"input" },
  { key: 9, label: `创建时间`, prop: `createdTime`, minWidth: 135, visible: false,dialogVis:false,type:"date" },
  { key: 10, label: `更新时间`, prop: `updatedTime`, minWidth: 135,  visible: false,dialogVis:false,type:"date" },
]);

const areaColumns = ref([
  { key: 0, label: '库区ID', prop: 'id', minWidth: 135, visible: false,dialogVis:false,type:"input" },
  { key: 0, label: '库区编号', prop: 'areaNo', minWidth: 200, visible: false,dialogVis:false,type:"input",query:true,queryType:'input' },
  { key: 1, label: '所属仓库', prop: 'warehouseId', minWidth: 160, visible: false,dialogVis:false,type:"input" },
  { key: 2, label: '库区名称', prop: 'name', minWidth: 135, visible: false ,dialogVis:true,type:"input",query:true,queryType:'input'},
  { key: 3, label: '库区描述', prop: 'description', minWidth: 135, visible: false,dialogVis:true,type:"input" },
  { key: 4, label: '创建时间', prop: 'createdTime', minWidth: 135, visible: false,dialogVis:false,type:"date" },
  { key: 5, label: '更新时间', prop: 'updatedTime', minWidth: 135, visible: false,dialogVis:false,type:"date" },
  // { key: 6, label: '创建人', prop: 'createBy', minWidth: 135, visible: false,dialogVis:false,type:"input" },
  // { key: 7, label: '修改人', prop: 'updateBy', minWidth: 135, visible: false,dialogVis:false,type:"input" }
]);

const shelfColumns = ref([
  { key: 0, label: '货架ID', prop: 'id', minWidth: 135, visible: false,dialogVis:false,type:"input" },
  { key: 0, label: '货架编号', prop: 'shelfNo', minWidth: 200, visible: false,dialogVis:false,type:"input",query:true,queryType:'input' },
  { key: 1, label: '所属库区', prop: 'areaId', minWidth: 160, visible: false,dialogVis:false,type:"select" },
  { key: 2, label: '货架名称', prop: 'name', minWidth: 135, visible: false,dialogVis:true,type:"input",query:true,queryType:'input' },
  { key: 3, label: '创建时间', prop: 'createdTime', minWidth: 135, visible: false },
  { key: 4, label: '更新时间', prop: 'updatedTime', minWidth: 135, visible: false },
  // { key: 5, label: '创建人', prop: 'createBy', minWidth: 135, visible: false },
  // { key: 6, label: '修改人', prop: 'updateBy', minWidth: 135, visible: false }
])

const locationColumns = ref([
  { key: 0, label: '货位ID', prop: 'id', minWidth: 135, visible: false },
  { key: 1, label: '所属货架', prop: 'shelfId', minWidth: 180, visible: false },
  { key: 2, label: '货位编码', prop: 'locationNo', minWidth: 200, visible: false,query:true,queryType:'input' },
  { key: 3, label: '货位状态', prop: 'status', minWidth: 135, visible: false },
  { key: 4, label: '创建时间', prop: 'createdTime', minWidth: 135, visible: false },
  { key: 5, label: '更新时间', prop: 'updatedTime', minWidth: 135, visible: false },
  // { key: 6, label: '创建人', prop: 'createBy', minWidth: 135, visible: false },
  // { key: 7, label: '修改人', prop: 'updateBy', minWidth: 135, visible: false },
  { key: 8, label: '新增多少个货位', prop: 'locationCount', width: 135, visible: true,dialogVis:true,type:"input" },
]);

const warehouseNameList = ref([])
const areaNameList = ref([])
const shelfNameList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    location: null,
    warehouseStatus: null,
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    location: [
      { required: true, message: "仓库位置不能为空", trigger: "blur" }
    ],
    capacity: [
      { required: true, message: "仓库容量不能为空", trigger: "blur" }
    ],
    createdTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updatedTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
    warehouseStatus: [
      { required: true, message: "仓库类型不能为空", trigger: "change" }
    ],
    storageFee: [
      { required: true, message: "仓储费不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (!/^\d+$/.test(value)) {
            callback(new Error("仓储费只能是数字"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    locationCount: [
      { required: true, message: "新增多少个货位不能为空", trigger: "blur" }
    ],
  },
});

const { queryParams, form, } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  const listFunctions = {
    1: listWarehouse,
    2: listAreaByPid,
    3: listShelfByPid,
    4: listLocationByPid,
  };
  queryParams.value.id = clickNode.value.id
  listFunctions[node.value](queryParams.value).then(response => {
    tableList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
  };
  proxy.resetForm(`${refMap[node]}`);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  console.log(queryParams.value);
  proxy.resetForm(`${refMap[node]}`);
  Object.keys(queryParams.value).forEach(key => {
      if (key !== 'pageNum' && key !== 'pageSize') {
        queryParams.value[key] = null;
      }
  });
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$refs[refMap.value[node.value]]?.clearValidate();
  reset();
  open.value = true;
  const titles = {
    1: "添加仓库管理",
    2: "添加库区管理",
    3: "添加货架",
    4: "添加货位",
  };
  title.value = titles[node.value];
}

/** 修改按钮操作 */
function handleUpdate(row) {
  proxy.$refs[refMap.value[node.value]]?.clearValidate();
  reset();
  const _id = row.id || ids.value;
  const fetchFunctions = {
    1: getWarehouse,
    2: getArea,
    3: getShelf,
    4: getLocation,
  };
  
  fetchFunctions[node.value](_id).then(response => {
    form.value = response.data;
    open.value = true;
    const titles = {
      1: "修改仓库管理",
      2: "修改库区管理",
      3: "修改货架",
      4: "修改货位",
    };
    title.value = titles[node.value];
  });
  getTree()
}

/** 提交按钮 */
const submitForm = () => {
  const submitFunctions = {
    1: submitFormWarehouse,
    2: submitFormArea,
    3: submitFormShelf,
    4: submitFormLocation,
  };

  submitFunctions[node.value]();
  getTree()
  if(node.value==1){
    queryWarehouse()
  }else if(node.value==2){
    queryArea()
  }else if(node.value==3){
    queryShelf()
  }
}

function submitFormWarehouse() {
  validateAndSubmit("warehouseRef", form.value, updateWarehouse, addWarehouse);
}

function submitFormArea() {
  form.value.warehouseId = clickNode.value.id
  validateAndSubmit("areaRef", form.value, updateArea, addArea);
}

function submitFormShelf() {
  form.value.areaId = clickNode.value.id
  validateAndSubmit("shelfRef", form.value, updateShelf, addShelf);
}

function submitFormLocation() {
  form.value.shelfId = clickNode.value.id
  validateAndSubmit("locationRef", form.value, updateLocation, addAllLocation);
}

function validateAndSubmit(refName, formData, updateFunc, addFunc) {
  proxy.$refs[refName].validate(valid => {
    if (valid) {
      const action = formData.id != null ? updateFunc : addFunc;
      action(formData).then(response => {
        proxy.$modal.msgSuccess(formData.id != null ? "修改成功" : "新增成功");
        open.value = false;
        getList();
        getTree()
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  const deleteOperations = {
    1: { confirmMsg: '仓库管理编号为"' + _ids + '"的数据项', delFunc: delWarehouse },
    2: { confirmMsg: '库区管理编号为"' + _ids + '"的数据项', delFunc: delArea },
    3: { confirmMsg: '货架管理编号为"' + _ids + '"的数据项', delFunc: delShelf },
    4: { confirmMsg: '货位管理编号为"' + _ids + '"的数据项', delFunc: delLocation }
  };

  const operation = deleteOperations[node.value];

  if (operation) {
    proxy.$modal.confirm('是否确认删除' + operation.confirmMsg + '？')
      .then(() => {
        return operation.delFunc(_ids);
      })
      .then(() => {
        getList();
        getTree()
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('warehouseManagement/warehouse/export', {
    ...queryParams.value
  }, `warehouse_${new Date().getTime()}.xlsx`)
}

getList();

// tree
const warehouseOptions = ref([
    {
        "id": 0,
        "name": "仓库管理",
        nodeId:1,
        "children": []
    }
])
/** 节点单击事件 */
function handleNodeClick(item) {
  console.log(proxy);
  
  node.value = item.nodeId
  clickNode.value = item
  console.log("节点",item);
  if(item.nodeId==2){
    columns.value = areaColumns.value
  }else if(item.nodeId==3){
    columns.value = shelfColumns.value
  }else if(item.nodeId==4){
    columns.value = locationColumns.value
  }else{
    columns.value = warehouseColumns.value
  }
  
  nextTick(() => {
    console.log(refMap.value[node.value]);
    
    proxy.$refs[refMap.value[node.value]]?.clearValidate(); // 重置表单，清除上次的校验状态
  });
  getList();
};
watch(node, (oldV,newV) => {
  console.log(oldV,newV);
  console.log(refMap.value[newV].value);
  
  proxy.$refs[refMap.value[newV]]?.clearValidate()
})

const warehouseTreeRef = ref(null);
onMounted(() =>{
  columns.value = warehouseColumns.value
  getTree()
  queryWarehouse()
  queryArea()
  queryShelf()
  
  // 默认选中根节点
  warehouseTreeRef.value.setCurrentKey(0);
})
/**
 * 获取所有仓库
 */
const queryWarehouse = () =>{
  listWarehouse({pageNum:1,pageSize:10000}).then(response => {
    warehouseNameList.value = response.rows;
  });
}
/**
 * 获取所有库区
 */
const queryArea = () =>{
  listArea({pageNum:1,pageSize:10000}).then(response => {
    areaNameList.value = response.rows;
  });
}
/**
 * 获取所有库位
 */
const queryShelf = () =>{
  listShelf({pageNum:1,pageSize:10000}).then(response => {
    shelfNameList.value = response.rows;
  });
}
const getTree = () =>{
  getWarehouseAll().then((res) =>{
    console.log(res);
    let data = res.data.map(warehouse => {
        // 设置仓库
        const warehouseNode = {
            ...warehouse,
            nodeId: 2,
            children: warehouse.areas.map(area => {
                // 设置库区
                const areaNode = {
                    ...area,
                    nodeId: 3,
                    children: area.shels.map(shelf => {
                        // 设置货架
                        return {
                            ...shelf,
                            nodeId: 4,
                        };
                    })
                };
                return areaNode;
            })
        };
        return warehouseNode;
    });
    warehouseOptions.value[0].children = data
  })
}

const getName=(type,id)=>{
  if(type=="warehouse"){
    const warehouse = warehouseNameList.value.find(item => item.id === id);
      return warehouse ? warehouse.name : '未知区域'; 
  }else if(type=="area"){
    const area = areaNameList.value.find(item => item.id === id);
      return area ? area.name : '未知区域'; 
  }else if(type=="shelf"){
    const shelf = shelfNameList.value.find(item => item.id === id);
    return shelf ? shelf.name : '未知区域'; 
  }else if(type=="warehouseStatus"){
    const status = wms_warehouse_status.value.find(item => item.value == id)
    return status ? status.label : id; 
  }else if(type=="status"){
    const status = id==0?"空闲":"占用"
    return status
  }
}
</script>
<style lang="scss" scoped>
.formBox{
  ::v-deep .el-select__selection{
    width:100px;
  }
}
</style>
